﻿@Cofe ?= {}

$ = jQuery
Entry = Cofe.Entry
EntryList = Cofe.EntryList
MetaItem = Cofe.MetaItem
Link = Cofe.Link
utils = Cofe.utils


class EntryMetaView extends Spine.Controller  
  metadataTemplate : $.templates("#metadataTemplate") # for key,value pair
  #actionTemplate : $.templates("#actionTemplate")     # for url
  elements : 
    ".metadata" : "uiMetadataList"
    "#map_canvas" : "uiMapCanvas"
    ".actions" : "uiActionList"
    "#dlgAddTag" : "dlgAddTag"
    "#dlgAddTag #tagName" : "uiTagName"

  init : () ->
    @

  changeEntries : (entries) ->    
    @entries = entries
    #If only 1 entry, get detail entry and refresh, otherwise refresh non-detail entry.
    if @entries.length is 1 
      #console.log(@entries[0].links.self.url)
      console.log "changeEntries"
      console.log @entries[0].links.self.url
      $.getJSON(@entries[0].links.self.url, {}
        (xhr, s, e) =>     
          #console.log "getJson"       
          @entries = [Entry.fromJson(xhr, true)]
          @refresh() 
      ).fail((err) => console.log err)
    else @refresh()

  createMetaItem : (key, value) ->
    new MetaItem({ key : key, value : value, templateKey : @metadataTemplate })
  
  updateMapPos : (entry, mapPos) ->
    lon = entry.metadata.gPSLongitude
    lat = entry.metadata.gPSLatitude
    if (lon isnt 0 and lon isnt undefined and lat isnt 0 and lat isnt undefined)
         mapPos.push( { lat : lat, lon : lon, label : entry.label  } )       

  buildMetadata : (entries) =>
    actions = []
    mapPos = []

    if entries.length is 1
      metaItem = (@createMetaItem(k, entries[0].metadata[k]) for k of entries[0].metadata)      

      @updateMapPos(entries[0], mapPos)

      if entries[0].type is "directory"
        actions.push("createFolder")
        actions.push("refresh")
      if utils.extractFilepath(@entries[0].path) isnt undefined
        actions.push("delete")
        
      
      metaItem.splice(0, 0, 
        @createMetaItem("Path", entries[0].path)        
        @createMetaItem("Id", entries[0].id)
      )

      if entries[0].links.thumbnail isnt undefined
        metaItem.push(@createMetaItem("Thumbnail", entries[0].links.thumbnail.url))
    else 
      tags = []
      for e in entries  
        tags = $.union(tags, e.metadata.tagsArray, [])
        @updateMapPos(e, mapPos)
      
      actions.push("delete")
      metaItem = [
        @createMetaItem("selected " + entries.length + " items")
        @createMetaItem("ParentPath", utils.extractFilepath(@entries[0].path))      
        @createMetaItem("tags", tags.sort().join())        
      ]
    #console.log mapPos
    
    for m in metaItem
      if m.key is "Tags"
        m.actions = ["edit", "add"]
    metaItem.push(new MetaItem({key : "actions", actions : actions, templateKey : @metadataTemplate }))

    for m in metaItem
      switch m.key
         when "Tags" then m.actionFunc = @tagsFunc
         when "Actions" then m.actionFunc = @actionFunc

    return { metaItem : metaItem, actions : actions, mapPos : mapPos }

  render : () =>    
    @remove()    
    for m in @metadata.metaItem
      @uiMetadataList.append(m.render())
  
  renderMap : (mapPos) =>
    if mapPos.length > 0         
       mapOptions = { 
         zoom: 16
         center: new google.maps.LatLng(mapPos[0].lat, mapPos[0].lon)
         mapTypeId: google.maps.MapTypeId.ROADMAP 
       }
       map = new google.maps.Map(@uiMapCanvas[0], mapOptions)  
       for p in mapPos
         marker = new google.maps.Marker({ 
           map:map
           title:p.label
           position: new google.maps.LatLng(p.lat, p.lon)
         });
       @uiMapCanvas.show()
    else @uiMapCanvas.hide()

  refresh : () =>
    #console.log "refresh"
    @metadata = @buildMetadata(@entries)
    @render()
    @renderMap(@metadata.mapPos)
    

  actionFunc : (sender, funcKey) =>
    if funcKey is "delete"
      
      for e in @entries
        $.ajax({ 
          url : e.links.self.url
          type : "DELETE"
          success: ((data, ts, xhr) => 
              log.debug("EntryMetaView: deleted " + e.path)
              @trigger("deleted", @, e.id)
          )
          error : ((data, ts, xhr) =>
              log.error("EntryMetaView: delete " + e.path + " (failed)")
              @trigger("error", @, e.id, "delete")
          )
          contentType:"application/json; charset=utf-8"
        })
        
    if funcKey is "refresh"
      for e in @entries
        $.post(e.links.refresh.url)
      
    if funcKey is "createFolder"
      folderName = utils.prompt("New folder","")
      json = new Object()
      json.name = folderName
      json.type = "folder"
      
      $.ajax({ 
          url : @entries[0].links.self.url
          type : "PUT"
          data : json
          dataType: "json"
          success: ((data, ts, xhr) => 
              entry = Cofe.Entry.fromJson(data)
              log.debug("EntryMetaView: created " + entry.path)
              @trigger("created", @, entry.id)              
          )
          error : ((data, ts, xhr) =>
              console.log "failed"
              @trigger("error", @, @entries[0].id, "create")
          )
          contentType:"application/json; charset=utf-8"
      })

  tagsFunc : (sender, funcKey) =>
    
    if funcKey is "edit"
       sender.isEditing = true
       sender.actions = ["save"]
       sender.render()

    else if funcKey is "add"
         addedValues = utils.prompt("New tag","")
         if addedValues isnt "" and addedValues isnt null then @addTags(addedValues) 
         sender.render()
    
    else if funcKey is "save"
         sender.isEditing = false
         sender.actions = ["edit", "add"]
         removedValues = (cb.value for cb in $("input:checkbox:not(:checked)", sender.el)).toString()
         if removedValues isnt "" and removedValues isnt null then @removeTags(removedValues) 
         sender.render()

  modifyTags : (tagNames, isAdd) ->
      url = if isAdd then "/api/entryList/AddTag" else "/api/entryList/RemoveTag"
      url += "?TagNames="+tagNames
      eList = EntryList.fromEntries(@entries)
      json = eList.toJson()
      $.ajax({
          url: url,
          type: 'POST',          
          contentType: 'application/json; charset=utf-8',
          data: json,
          dataType: 'json',
          async: true,
          success: (xhr,s, e) => 
            log.debug("EntryMetaView: modifyTags " + @entries.length + " items")
            ids = (e.id for e in @entries)
            Entry.remove(id) for id in ids #clear cache
            newEntryList = EntryList.fromJson(xhr, true)
            @changeEntries(newEntryList.entries)
      })

  addTags : (tagNames) =>
      @modifyTags(tagNames, true)

  removeTags : (tagNames) =>
      @modifyTags(tagNames, false)



   


    
  remove : () =>
    @uiMetadataList.empty()

 

Cofe.EntryMetaView = EntryMetaView